                                                                          //
//  PGStatusList.swift
//  PGWeibo
//
//  Created by Apple on 15/11/9.
//  Copyright © 2015年 Apple. All rights reserved.
//

import Foundation
import SDWebImage
class PGStatusListViewModel {
    /// 微博数据数组 - 上拉/下拉刷新
    lazy var statusViewModelList = [PGStatusViewModel]()
    /// 加载微博数据
    func loadStatusList(finished: (isSuccessed: Bool)->()) {
        PGNetworkTools.sharedTools.loadStatus { (result, error) -> () in
            
            if error != nil {
                print("出错了...")
                finished(isSuccessed: false)
                return
            }
            guard let list = result!["statuses"] as? [[String: AnyObject]]  else {
                finished(isSuccessed: false)
                print("格式错误")
                return
            }
            
            var dataList = [PGStatusViewModel]()
            for dict in list {
                //遍历数组 字典转模型
                let status = PGStatus(dict: dict)
                 dataList.append(PGStatusViewModel(status: status))
            }
            //拼接数据
            self.statusViewModelList = self.statusViewModelList + dataList
            
            
            //缓存单张图片
            self.cacheSingleImage(dataList, finished: finished)
        }
    }
    //缓存单张图片
    func cacheSingleImage(dataList: [PGStatusViewModel], finished: (isSuccessed: Bool)->()) {
        //创建调度组
        let group = dispatch_group_create()
        // 缓存数据长度
        var dataLength = 0
        
        //遍历数组
        for vm in dataList {
            
            //判断是否为单张图片
            if vm.thumbnailUrls?.count != 1 {
                continue
            }
            //获取单张图片的url
            let url = vm.thumbnailUrls!.first
            
            //进组
            dispatch_group_enter(group)
            
            //用SDWebImage
            SDWebImageManager.sharedManager().downloadImageWithURL(url, options: [SDWebImageOptions.RefreshCached, SDWebImageOptions.RetryFailed], progress: nil, completed: { (image, _, _, _, _) -> Void in
                
                if let img = image,
                    let data = UIImagePNGRepresentation(img) {
                        dataLength += data.length
                }
                
                //出组
                dispatch_group_leave(group)
            })

        }
        
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
            
            print("缓存完成 \(dataLength / 1024) K")
            //回调
            finished(isSuccessed: true)
        }
    }
    
  
}